//
//  MNDFinaceListPageViewController.m
//  minidai
//
//  Created by 谭谭伟 on 17/5/20.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDFinaceListPageViewController.h"
#import "MNDFinanceDateModel.h"
#import "MNDCreditorsModel.h"
#import "MNDFinanceListModel.h"
#import "MNDFinanceTableViewCell.h"
#import "SYRefreshControl.h"
#import "MNDFinanceNavMoreView.h"
#import "JhtHorizontalMarquee.h"
#import "MNDFListAlertViewController.h"
#import "MNDLoginUserModel.h"
#import "MNDFinanceDetailViewController.h"
#import "MNDCreditorDetailViewController.h"
#import "MNDFirstDetailCell.h"
#import "MNDFinanceViewController.h"
#import "MNDCreditorInvestViewController.h"
#import "MNDDepositAlertViewController.h"
#import "MNDDetaiRootViewController.h"
#import "MNDCreditorDetaiRootViewController.h"
#import "MNDCreditorHRdetailViewController.h"
#import "MNDUserModel.h"
#import "MNDRiskAssessWebViewController.h"
#import "UIImage+JKColor.h"

#import "MNDUserModel.h"

@interface MNDFinaceListPageViewController () <UITableViewDelegate,UITableViewDataSource>



@property (strong,nonatomic) MNDFinanceListModel *financeListModel;

//其他类型模型数组
@property (strong,nonatomic) NSMutableArray *financeModelArray;
//债转模型数组
@property (strong,nonatomic) NSMutableArray *creditorModelArray;
//没有选择投资类型，下拉刷新页数
@property (assign,nonatomic) NSInteger pageNumber;
//选择投资类型，下拉刷新页数
@property (assign, nonatomic) NSInteger pageNumberType;
//债权转让数据页码
@property (assign, nonatomic) NSInteger creditorPageNumber;

/* 是否隐藏第一组cell */
@property (assign, nonatomic) BOOL cellHidden;

@property (weak, nonatomic) IBOutlet UIButton *navFinanceBtn;

/* 记录选择投资的类型的通知传过来的字典 */
@property (strong, nonatomic) NSDictionary *userDict;



/* MNDFinanceNavMoreView */
@property (strong, nonatomic) MNDFinanceNavMoreView *mndFinanceNavMoreView;


//跑马灯view
@property (weak, nonatomic) IBOutlet UIView *cycleView;
@property (weak, nonatomic) IBOutlet UILabel *cycleLabel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tipHeightConstraint;

/* 水平滚动paomadeng */
//@property (strong, nonatomic) JhtHorizontalMarquee *horizontalMarquee;

/* 无数据时的占位图 */
//@property (strong, nonatomic) UIImageView *placeHolderView;
@property (strong, nonatomic) UILabel *placeLabel;

@property (weak, nonatomic) IBOutlet UIView *placeHolderView;

@property (nonatomic) BOOL showTips;

@property (strong, nonatomic) UILabel *titleLabel;

@property (strong, nonatomic) UIView *placeHolderMaskView;

@property (nonatomic, copy) NSString *userPhone;

@property(nonatomic, strong) MNDUserModel *userModel;

/**
 普通标网络请求id
 */
@property (nonatomic, strong) NSString *financeNetworkId;

/**
 债转标网络请求id
 */
@property (nonatomic, strong) NSString *creditorNetworkId;
//选择的类型 0全部1车商贷2车盈贷3车商贷+车盈贷
@property (strong, nonatomic) NSString *borrowType;

@end

@implementation MNDFinaceListPageViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (@available(iOS 11, *)) {
        self.financeListTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    //接收通知
    [self receiveNotification];

    [self setNavTitle];
    self.financeListTableView.estimatedRowHeight = 120.0;
    self.financeListTableView.rowHeight = UITableViewAutomaticDimension;
    [self setupUI];
    [self initialBarbuttonItems];
    self.showTips = YES;
    [self creatMaskView];
    
    
}

- (void)setNavTitle {
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 44)];
    self.navigationItem.titleView = self.titleLabel;
    self.titleLabel.text = @"出借项目";
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
}

- (void)initialBarbuttonItems {

    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    
    UIImage *image = [UIImage imageNamed:@"finance_invest_btn-1"];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage: image
                                                             style:UIBarButtonItemStylePlain
                                                            target:self
                                                            action:@selector(navClickMore:)];
    [item setTitleTextAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Regular" size:14.0]} forState:UIControlStateNormal];
    [item setTintColor:kColorBackButtonColor];
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItems = @[spaceItem, item];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.financeNetworkId = nil;
    self.creditorNetworkId = nil;
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage jk_imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];

    [self.financeListTableView.mj_header beginRefreshing];
    
    self.userModel = [[MNDUserModel alloc] init];
    if ([MNDLoginUserModel isUserLogin]) {
        
        [self loadUserInfos];
    }
    
    //请求自动投标描述
    [self loadAutoTenderDescribe];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    if (self.financeNetworkId) {
        [XMCenter cancelRequest:self.financeNetworkId];
    }
    if (self.creditorNetworkId) {
        [XMCenter cancelRequest:self.creditorNetworkId];
    }
    // 关闭跑马灯
//    [_horizontalMarquee marqueeOfSettingWithState:MarqueeShutDown_H];
}

#pragma mark -懒加载
- (NSMutableArray *)financeModelArray {
    if (!_financeModelArray) {
        _financeModelArray = [NSMutableArray array];
    }
    return _financeModelArray;
}

- (NSMutableArray *)creditorModelArray {
    if (!_creditorModelArray) {
        _creditorModelArray = [NSMutableArray array];
    }
    return _creditorModelArray;
}

#pragma mark -加载数据

- (void)loadUserInfos {
    
    WeakSelf(self);
    [APIManager sendRequestWithPath:API_USER_BASE_INFO
                         parameters:[MNDSign signedParam]
                             method:kXMHTTPMethodGET
                          onSuccess:^(ResponseModel *responseModel) {
                              
                              if (responseModel.status == ResponseSuccess) {
                                  [NetworkProgressHUD hideHud];
                                  weakself.userModel = [MNDUserModel mj_objectWithKeyValues:responseModel.data];
                                  NSLog(@"data: %@", responseModel.data);
                              } else {
                                  NSDictionary *dict = responseModel.msg;
                                  if (dict && dict.count > 0) {
                                      [NetworkProgressHUD showHudMsg:dict[@"error"]];
                                  } else {
                                      [NetworkProgressHUD showHudMsg:@"获取数据失败"];
                                  }
                              }
                              
                          } onFailure:^(NSError *error) {
                              [NetworkProgressHUD showHudNetworkError:error];
                          }];
}

- (void)loadData:(BOOL)isPullDown {
//    __weak typeof(self) weakSelf = self;

    //请求的参数
    NSDictionary *parametersDict;
    //如果下拉
    if (isPullDown) {
        _pageNumber = 1;
        //清空数组
//        self.financeModelArray = nil;
//        self.creditorModelArray = nil;
    }else {
        _pageNumber++;
    }
    NSString *perpage = [NSString stringWithFormat:@"%zd",_pageNumber];
    parametersDict = @{@"perpage":perpage,
                       @"borrow_type":@"3",
                       @"pagesize": @"10",
                       @"deadline":@""
                       };

    //选择了类型
    NSString *perpageMore;
    if (self.userDict != nil) {
        //每次先取到传过来的页码
        perpageMore = [self.userDict objectForKey:@"perpage"];
        //类型
    
//        NSString *borrowType = [self.userDict objectForKey:@"borrow_type"];
        
        //期限
        NSString *deadline = [self.userDict objectForKey:@"deadline"];
        _pageNumberType = perpageMore.integerValue;
        //如果下拉
        if (isPullDown) {//展示第一页数据
            _pageNumberType = 1;
        } else {
            //上拉加1
            _pageNumberType++;
        }
        perpageMore = [NSString stringWithFormat:@"%zd",_pageNumberType];
        //重新设置请求参数
        self.userDict = @{@"perpage":perpageMore,
                          @"borrow_type":@"3",
                          @"deadline":deadline,
                          @"pagesize":@"10"
                          };
//        self.borrowType = borrowType;
        if (self.isCreditor) {

            [self loadCreditorsData:isPullDown];
            return;
        }
        parametersDict = self.userDict;

    }
    //请求数据
    NSDictionary *params = [MNDSign signedParamWithDict:parametersDict];
    if(isPullDown) {
//        [NetworkProgressHUD showHud];
    }
    WeakSelf(self);
    
    self.financeNetworkId = [APIManager sendRequestWithPath:API_FINANCE_LIST parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        NSLog(@"response: %@",responseModel.data);
        if (responseModel.status == ResponseSuccess) {
            weakself.financeListModel = [MNDFinanceListModel mj_objectWithKeyValues:responseModel.data];
            if (isPullDown) {
                [weakself.financeModelArray removeAllObjects];
                [weakself.creditorModelArray removeAllObjects];
            }

            [weakself configContents];
            
        }else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
        
        //        BOOL hasData = weakself.financeListModel.creditors.count > 0 && weakself.financeListModel.manages.count > 0;
        
        BOOL hasData = weakself.financeListModel.creditors.count > 0 || weakself.financeListModel.manages.count > 0;
        [SYRefreshControl configAfterLoading:weakself.financeListTableView hasData:hasData];
        
        [weakself.financeListTableView reloadData];
        [NetworkProgressHUD hideHud];
    } onFailure:^(NSError *error) {
        [SYRefreshControl configAfterLoading:weakself.financeListTableView hasData:(weakself.financeModelArray.count > 0 && weakself.creditorModelArray > 0)];
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

#pragma mark -加载债权转让数据
- (void)loadCreditorsData:(BOOL)isPullDown{
    
    __weak typeof(self) weakSelf = self;
    //请求参数
    NSDictionary *parametersDict;
    //如果下拉
    if (isPullDown) {//展示第一页数据
        _creditorPageNumber = 1;
    }else {//上拉加载后面几页数据
        
        _creditorPageNumber++;
        
    }
    parametersDict = @{@"perpage":@(_creditorPageNumber),
                       @"pagesize":@"10"
                       };
    
    NSDictionary *params = [MNDSign signedParamWithDict:parametersDict];
    //请求债权转让数据
    self.creditorNetworkId = [APIManager sendRequestWithPath:API_CREDITOR_LIST parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        NSLog(@"response: %@",responseModel);
        if (responseModel.status == ResponseSuccess) {
            weakSelf.financeListModel = [MNDFinanceListModel mj_objectWithKeyValues:responseModel.data];
            if (isPullDown) {
                [weakSelf.creditorModelArray removeAllObjects];
            }
            [weakSelf configContents];
        }else {
            if (isPullDown) {
                [weakSelf.view configBlankPage:SYBlankPageTypeError hasData:NO reloadButtonBlock:^(id sender) {
                    [weakSelf loadData:isPullDown];
                }];
            }
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
        [SYRefreshControl configAfterLoading:weakSelf.financeListTableView hasData:weakSelf.financeListModel.creditors.count];
        //        [SYRefreshControl configAfterLoading:weakSelf.financeListTableView hasData:weakSelf.financeListModel.manages];
        
        [self.financeListTableView reloadData];
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
        [SYRefreshControl configAfterLoading:weakSelf.financeListTableView hasData:(weakSelf.financeModelArray.count > 0 && weakSelf.creditorModelArray > 0)];
    }];
}

- (void)loadAutoTenderDescribe {
    
    kdeclare_weakself;
    [APIManager sendRequestWithURL:API_AUTO_TENDER_TIPS parameters: [MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakSelf.cycleLabel.text = responseModel.data[@"auto_tender_describe"];
        }
    } onFailure:^(NSError *error) {
        
    }];
    
}


#pragma mark -搭建界面
- (void)setupUI {
    WeakSelf(self);
    
    [SYRefreshControl configGifMJRefresh:self.financeListTableView refreshType:MJRefreshSupportALl beginRefresh:YES timeLabelHidden:YES stateLabelHidden:YES refreshBlock:^{
        
        if (weakself.isCreditor) {
            [weakself loadCreditorsData:YES];
        }else {
            [weakself loadData:YES];
        }
    } loadMoreBlock:^{
        if (weakself.isCreditor) {
            [weakself loadCreditorsData:NO];
        }else {
            [weakself loadData:NO];
        }
    }];
    
    NSArray *views=  [[NSBundle mainBundle]loadNibNamed:@"MNDFinanceNavMoreView" owner:nil options:nil];
    MNDFinanceNavMoreView *mndFinanceNavMoreView = views[0];
    mndFinanceNavMoreView.frame = CGRectMake(0, 0,kScreenWidth , 250);
    //    mndFinanceNavMoreView.hidden = YES;
    //记录
    self.mndFinanceNavMoreView = mndFinanceNavMoreView;
    //遮罩图
    UIView *maskView = [[UIView alloc]initWithFrame:CGRectMake(0, -kScreenHeight, kScreenWidth, kScreenHeight)];
    maskView.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5];
    [maskView addSubview:mndFinanceNavMoreView];
    maskView.hidden = YES;
    self.maskView = maskView;
    [self.view addSubview:maskView];
    //为maskView添加点击事件
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hidenExitMaskView)];
    [maskView addGestureRecognizer:tapGesture];
}


#pragma mark -加载数据后赋值
- (void)configContents {
    [self.creditorModelArray addObjectsFromArray:self.financeListModel.creditors];
    [self.financeModelArray addObjectsFromArray:self.financeListModel.manages];
    if ([_borrowType isEqualToString:@"3"]) {
        if (self.creditorModelArray.count <= 0) {
            self.placeHolderMaskView.hidden = NO;
        }else {
            self.placeHolderMaskView.hidden = YES;
        }
    }else {
        if ((self.financeModelArray.count <= 0) && (self.creditorModelArray.count <= 0)) {
            self.placeHolderMaskView.hidden = NO;
        }else {
            self.placeHolderMaskView.hidden = YES;
        }
    }
}

#pragma mark -投资列表nav点击事件

- (IBAction)navClickMore:(UIButton *)sender {
    if (!self.navRightBtnClick) {
        //显示遮罩后让tabview不能滚动
        self.financeListTableView.scrollEnabled = NO;
        //取消遮罩的隐藏
        self.maskView.hidden = NO;
        //        self.mndFinanceNavMoreView.hidden = NO;
        [UIView animateWithDuration:0.25 animations:^{
            self.maskView.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight);
        }];
        UITableViewHeaderFooterView *headerView = [self.financeListTableView headerViewForSection:1];
        headerView.hidden = YES;
        //    self.navigationController.navigationBarHidden = YES;
//        self.tabBarController.tabBar.hidden = YES;
        self.navRightBtnClick = YES;
    } else {
        [UIView animateWithDuration:0.25 animations:^{
             [self hidenExitMaskView];
        }];
    }
}

#pragma mark   接收通知
- (void)receiveNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadDataWithSelectType:) name:@"kFinanceListType" object:nil];
}

//选择投资类型执行通知事件
- (void)loadDataWithSelectType:(NSNotification *)notification {
    
    self.userDict = notification.userInfo;
    // @{@"borrow_type":borrowType,@"deadline":deadline};
    NSString *borrowType = [self.userDict objectForKey:@"borrow_type"];
    if ([borrowType isEqualToString:@"1"]) {
        self.titleLabel.text = @"车商贷";
        
    } else if([borrowType isEqualToString:@"2"]) {
        self.titleLabel.text = @"车盈贷";
        self.navigationItem.titleView = self.titleLabel;
        
    } else if([borrowType isEqualToString:@"3"]) {
        self.titleLabel.text = @"债权转让";
        self.navigationItem.titleView = self.titleLabel;
        
    } else {
        self.titleLabel.text = @"出借项目";
        self.navigationItem.titleView = self.titleLabel;
    }
    //置空原来的数据
    self.financeModelArray = nil;
    self.creditorModelArray = nil;
    [self loadData:YES];
    [self hidenExitMaskView];
}

#pragma mark -退出隐藏投资类型选择
- (void)hidenExitMaskView {
    self.navRightBtnClick = NO;
    //显示遮罩后让tabview能够滚动
    self.financeListTableView.scrollEnabled = YES;
    //动画展示
    [UIView animateWithDuration:0.25 animations:^{
        self.maskView.frame = CGRectMake(0, -kScreenHeight, kScreenWidth, kScreenHeight);
    }];
    //显示组头，nav,tabbar,隐藏遮罩
    UITableViewHeaderFooterView *headerView = [self.financeListTableView headerViewForSection:1];
    headerView.hidden = NO;
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = NO;
    self.maskView.hidden = YES;
}

#pragma mark UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return (self.creditorModelArray.count + self.financeModelArray.count );

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MNDFinanceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FinanceReuseCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //债权转让有数据
    if ((self.creditorModelArray.count > 0) && (indexPath.row < self.creditorModelArray.count)) {
        
        MNDCreditorsModel *creditorsModel = self.creditorModelArray[indexPath.row];
        MNDCreditorsModel *firstCreditorsModel = self.creditorModelArray[0];
        //隐藏投资按钮
        if ([firstCreditorsModel.status isEqualToString:@"1"] &&indexPath.row == 0) {
            MNDFirstDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MNDFirstDetailCell"];
            cell.goInvestButton.tag = 101;
            //点击立即投资按钮
            [cell.goInvestButton addTarget:self action:@selector(goInvestAction:) forControlEvents:UIControlEventTouchUpInside];
            cell.creditorsModel = creditorsModel;
            return cell;
        }else {
            cell.goInvestBtn.hidden = YES;
        }
        cell.creditorsModel = creditorsModel;
        cell.progressView.progress = 0.8;
        
    } else {
        if (self.financeModelArray.count > 0) {
            if (self.creditorModelArray.count <= 0) {
                MNDFinanceDateModel *firstFinanceModel = self.financeModelArray[0];
                if ([firstFinanceModel.txt_status isEqualToString:@"进行中"] && indexPath.row == 0 ) {
                    MNDFirstDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MNDFirstDetailCell"];
                    cell.firstFinanceModel = firstFinanceModel;
                    cell.goInvestButton.tag = 102;
                    [cell.goInvestButton addTarget:self action:@selector(goFinanceInvestAction:) forControlEvents:UIControlEventTouchUpInside];
                    return cell;
                }
            }else {
                cell.goInvestBtn.hidden = YES;
            }
            MNDFinanceDateModel *financeModel = self.financeModelArray[indexPath.row - self.creditorModelArray.count];
            cell.financeModel = financeModel;
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
    //债权转让有数据
    if ((self.creditorModelArray.count > 0) && (indexPath.row < self.creditorModelArray.count)) {
        if (kScreenWidth < 414) {//ipad
            UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Detail" bundle:nil];
            
            MNDCreditorDetaiRootViewController *creditorDetailVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDCreditorDetaiRootViewController"];
            MNDCreditorsModel *creditorsModel = self.creditorModelArray[indexPath.row];
            creditorDetailVC.borrowCode = creditorsModel.borrow_code;
            creditorDetailVC.creditorCode = creditorsModel.creditor_code;
            creditorDetailVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:creditorDetailVC animated:YES];
        }else {
            UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
            MNDCreditorHRdetailViewController *creditorDetailVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDCreditorHRdetailViewController"];
            MNDCreditorsModel *creditorsModel = self.creditorModelArray[indexPath.row];
            creditorDetailVC.borrowCode = creditorsModel.borrow_code;
            creditorDetailVC.creditorCode = creditorsModel.creditor_code;
            creditorDetailVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:creditorDetailVC animated:YES];

        }
    
    } else {
        if (self.financeModelArray.count > 0) {
            if (kScreenWidth <= 414) {//ipad
                UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Detail" bundle:nil];
                
                MNDDetaiRootViewController *detailVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDDetaiRootViewController"];
                MNDFinanceDateModel *financeModel = self.financeModelArray[indexPath.row - self.creditorModelArray.count];
                detailVC.brrowCode = financeModel.code;
                detailVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:detailVC animated:YES];
            } else {
                UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
                MNDFinanceDetailViewController *detailVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDFinanceDetailViewController"];
                MNDFinanceDateModel *financeModel = self.financeModelArray[indexPath.row - self.creditorModelArray.count];
                detailVC.brrowCode = financeModel.code;
                detailVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:detailVC animated:YES];
            }
        }
    }
}

//侧滑
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    //债权转让有数据
    if ((self.creditorModelArray.count > 0) && (indexPath.row < self.creditorModelArray.count)) {
        
        MNDCreditorsModel *creditorsModel = self.creditorModelArray[indexPath.row];
        if ([creditorsModel.status isEqualToString:@"1"]) {
            if (indexPath.row == 0) {
                return nil;
            }
            UITableViewRowAction *creditorRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"立即出借" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                if ([MNDLoginUserModel isUserLogin]) {//已登录
                    [self checkOpenDepositCreditor:indexPath.row];
                    
                } else {//未登录
                    [self goToLoginVC];
                }
                
            }];
            creditorRowAction.backgroundColor = GlobalColor;
            return @[creditorRowAction];
        } else {
            return nil;
        }
    } else if (self.financeModelArray.count > 0) {
        
        
        MNDFinanceDateModel *financeModel = self.financeModelArray[indexPath.row - self.creditorModelArray.count];
        if ([financeModel.txt_status isEqualToString:@"进行中"]) {
            
            UITableViewRowAction *financeRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"立即出借" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                if ([MNDLoginUserModel isUserLogin]) {//已登录
                    
                    [self checkOpenDepositFince:(indexPath.row - self.creditorModelArray.count)];
                }else {
                    [self goToLoginVC];
                }
            }];
            financeRowAction.backgroundColor = GlobalColor;
            return @[financeRowAction];
        } else {
            return nil;
        }
    } else {
        return nil;
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    //债权转让有数据
    if ((self.creditorModelArray.count > 0) && (indexPath.row < self.creditorModelArray.count)) {
        MNDCreditorsModel *creditorsModel = self.creditorModelArray[indexPath.row];
        if ([creditorsModel.status isEqualToString:@"1"]) {
            if (indexPath.row == 0) {
                return NO;
            }
            return YES;
        }else {
            return NO;
        }
    }else if(self.financeModelArray.count > 0){
        MNDFinanceDateModel *financeModel = self.financeModelArray[indexPath.row - self.creditorModelArray.count];
        if ([financeModel.txt_status isEqualToString:@"进行中"]) {
            if (indexPath.row == 0) {
                return NO;
            }
            return YES;
        }else {
            return NO;
        }
        
    }else {
        return NO;
    }
}

#pragma mark - action

//提示弹窗
- (IBAction)clickShowTip:(UIButton *)sender {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
    __weak MNDFListAlertViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDFListAlertViewController"];
    alertVC.tipStr = self.cycleLabel.text;
    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self addChildViewController:alertVC];
    //    __weak typeof(self) weakSelf = self;
    [alertVC.iKonwBtn bk_addEventHandler:^(id sender) {
        [UIView animateWithDuration:0.5 animations:^{
            alertVC.alertContainView.frame = CGRectMake(alertVC.alertContainView.frame.origin.x, kScreenHeight, alertVC.alertContainView.frame.size.width, alertVC.alertContainView.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
            self.cycleView.hidden = YES;
            self.tipHeightConstraint.constant = 0;
        }];
            } forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark -立即投资

//债转
- (void)goInvestAction:(UIButton *)sender {
    if (sender.tag == 101) {

        if (![MNDLoginUserModel isUserLogin]) {
            [self goToLoginVC];
            
            return;
        }
        
        [self confirmInvestSuccess];
    }
}

//非债转
- (void)goFinanceInvestAction:(UIButton *)sender {
    if (sender.tag == 102) {
        if (![MNDLoginUserModel isUserLogin]) {
            [self goToLoginVC];
            
            return;
        }
        
        [self confirmInvestSuccess];
    }
}

#pragma mark -没有登录，跳转到登录页面

- (void)goToLoginVC {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    UINavigationController *naviVC = [storyboard instantiateInitialViewController];
    
    [self presentViewController:naviVC animated:YES completion:^{
        
    }];
}

//债权侧滑判断
- (void)checkOpenDepositCreditor:(NSInteger)indexRow {
    
    //跳转到投资页面
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Finance" bundle:[NSBundle mainBundle]];
    MNDCreditorsModel *model = self.creditorModelArray[indexRow];
    MNDCreditorInvestViewController *creditorVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDCreditorInvestViewController"];
    creditorVC.borrowCode = model.borrow_code;
    creditorVC.creditorCode = model.creditor_code;
    creditorVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:creditorVC animated:YES];
}

//非债权
- (void)checkOpenDepositFince:(NSInteger)indexRow {
    
    //跳转到投资页面
    MNDFinanceDateModel *financeModel = self.financeModelArray[indexRow];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Finance" bundle:[NSBundle mainBundle]];
    MNDFinanceViewController *detailVC = [storyboard instantiateViewControllerWithIdentifier:@"financeVC"];
    detailVC.borrowCode = financeModel.code;
    detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)confirmInvestSuccess {
 
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Finance" bundle:[NSBundle mainBundle]];
    if (self.creditorModelArray.count > 0) {
        MNDCreditorsModel *model = self.creditorModelArray[0];
        MNDCreditorInvestViewController *creditorVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDCreditorInvestViewController"];
        creditorVC.borrowCode = model.borrow_code;
        creditorVC.creditorCode = model.creditor_code;
        creditorVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:creditorVC animated:YES];
        
    } else {
        if (self.financeModelArray.count > 0) {
            MNDFinanceViewController *detailVC = [storyboard instantiateViewControllerWithIdentifier:@"financeVC"];
            MNDFinanceDateModel *financeModel = self.financeModelArray[0];
            detailVC.borrowCode = financeModel.code;
            detailVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
    }
}

#pragma mark - 无数据显示图片
- (void)creatMaskView {
    UIView *maskView = [[UIView alloc]initWithFrame:self.view.bounds];
    maskView.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0];
    //    [self.view insertSubview:maskView aboveSubview:self.tableView];
    [self.financeListTableView addSubview:maskView];
    UIImageView *imgV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"blankpage_emptydata"]];
    UILabel *tipLabel = [[UILabel alloc]init];
    tipLabel.text = @"哎呀~这里空空如也~";
    tipLabel.font = [UIFont systemFontOfSize:14];
    tipLabel.textColor = kColorGray;
    
    [maskView addSubview:tipLabel];
    [maskView addSubview:imgV];
    
    imgV.layer.cornerRadius = imgV.bounds.size.height*0.5;
    imgV.clipsToBounds = YES;
    [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(maskView);
        make.centerY.equalTo(maskView).mas_offset(-80);
    }];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(imgV);
        make.top.equalTo(imgV.mas_bottom).offset(10);
    }];
    
    self.placeHolderMaskView = maskView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
